#!/bin/bash
# 初始化conda环境
environment_name="one_step"
source ~/anaconda3/etc/profile.d/conda.sh
conda activate "${environment_name}"

# 更新项目文件
project_path="/home/admin/one_step/one_step"
cd "${project_path}"
git pull

# 安装项目内 requirements.txt 的包
requirements_file="/home/admin/one_step/one_step/requirements.txt"
pip install -r "${requirements_file}" && echo "Installation succeeded" || { echo "Installation failed"; exit 1; }

# 4. 检查并重启某py项目
if pgrep -f "python ${project_path}/one_step.py" >/dev/null; then
    echo "项目已经在运行中，尝试提取当前task"
    # 发起一个HTTP GET请求
    GET_URL="http://localhost:5678/get_tasks"
    GET_RESPONSE=$(curl -s -X GET "$GET_URL")
    echo "GET response: $GET_RESPONSE"

    # 如果GET_RESPONSE不是json 或者 json.success非正确 则抛错误，阻断流程
    # 如果GET_RESPONSE.success非正确 则抛错误，阻断流程
    if [[ $(echo $GET_RESPONSE | jq -r '.success') != "true" ]]; then
        echo "GET request was not successful."
        exit 1
    fi

    echo "项目已经在运行中，尝试重启..."
    pkill -f "python ${project_path}/one_step.py"  # 杀掉原来的进程
    sleep 20  # 等待几秒，以确保进程已经完全停止

    log_file="/home/admin/one_step/logs/log.log"
    nohup python "${project_path}/one_step.py" start >"$log_file" 2>&1 &

    # 检查Flask应用是否成功启动
    max_retries=60
    retry_count=0
    while ! netstat -tuln | grep ":5678" >/dev/null; do
        sleep 3  # 等待3秒钟
        retry_count=$((retry_count + 1))
        if [ $retry_count -ge $max_retries ]; then
            echo "启动Flask应用失败"
            exit 1
        fi
    done
    echo "启动Flask应用成功"
    sleep 10  # 等待5秒钟
    # 使用GET请求返回的数据作为POST请求的JSON数据，这里仅保留GET_RESPONSE的data部分
    DATA_TO_POST=$(echo "$GET_RESPONSE" | jq '.data')
    echo "POST data: $DATA_TO_POST"
    POST_URL="http://localhost:5678/readd_tasks"
    POST_RESPONSE=$(curl -s -X POST -H "Content-Type: application/json" -d "$DATA_TO_POST" "$POST_URL")
    echo "POST response: $POST_RESPONSE"
    # 检查POST请求是否成功
    # 检查POST请求是否成功
    if [[ $(echo $POST_RESPONSE | jq -r '.success') == "true" ]]; then
        echo "任务恢复成功"
    else
        echo "任务恢复失败"
    fi
else
    echo "项目尚未启动，尝试启动..."
    log_file="/home/admin/one_step/logs/log.log"
    nohup python "${project_path}/one_step.py" start >"$log_file" 2>&1 &
    # 检查Flask应用是否成功启动
    max_retries=60
    retry_count=0
    while ! netstat -tuln | grep ":5678" >/dev/null; do
        sleep 3  # 等待3秒钟
        retry_count=$((retry_count + 1))
        if [ $retry_count -ge $max_retries ]; then
            echo "启动Flask应用失败"
            exit 1
        fi
    done
    echo "启动Flask应用成功"
fi